package com.tping.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 单线程版本
 *
 * 实现多客户端连接服务端
 * @author zhuwj
 */
public class SocketMultipleSingleThread {

    private int port = 8089;

    private ServerSocketChannel server;
    private Selector selector;

    public void initServer() throws IOException {
        server = ServerSocketChannel.open();
        server.configureBlocking(false); // 非阻塞
        server.bind(new InetSocketAddress(port));

        selector = Selector.open();
        server.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务端启动成功...");
    }

    public void start() throws IOException {
        initServer();

        for (;;){
            while (selector.select(10) > 0){  // 询问是否有事件 有则大于0
                Set<SelectionKey> selectedKeys = selector.selectedKeys();

                // 从多路复用器中获取有效KEY
                Iterator<SelectionKey> iterator = selectedKeys.iterator();

                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();   // 清空

                    if( key.isAcceptable()){
                        // 是否存在连接
                        acceptHandler(key);
                    }else if( key.isReadable() ){
                        // 是否有可读
                        readHandler(key);
                    }
                }
            }
        }
    }

    private void readHandler(SelectionKey key) {
        SocketChannel channel = (SocketChannel)key.channel();

        ByteBuffer buffer = (ByteBuffer) key.attachment();
        buffer.clear();
        try {
            int read = 0;
            for (;;){
                read = channel.read(buffer);
                if( read > 0 ){
                    buffer.flip();
                    while (buffer.hasRemaining()){
                        System.out.println("---------------------------------");
                        byte[] bytes = new byte[buffer.limit()];
                        buffer.get(bytes);
                        System.out.printf("接收到客户端内容：%s", new String(bytes));
                        ByteBuffer write = ByteBuffer.wrap("服务端接收到您的消息\n".getBytes());
                        channel.write(write);
                        System.out.println("---------------------------------");
                    }
                    buffer.clear();
                }else if( read == 0 ){
                    break;
                }else if( read < 0 ){
                    System.out.println("可能客户端已断开连接...");
                    channel.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void acceptHandler(SelectionKey key) throws IOException {
        ServerSocketChannel server = (ServerSocketChannel)key.channel();
        SocketChannel channel = server.accept();
        channel.configureBlocking(false); // 非阻塞

        ByteBuffer buffer = ByteBuffer.allocateDirect(5 * 1024);
        channel.register(selector, SelectionKey.OP_READ, buffer);

        System.out.println("=====================================");
        System.out.printf("新客户端：%s，成功建立连接...\n", channel.socket().getPort());
        System.out.println("=====================================");
    }

    public static void main(String[] args) throws IOException {
        new SocketMultipleSingleThread().start();
    }

}
